#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include "Log.hpp"

void Usage(std::string pro)
{
    // std::cout << "Usage:\n\t" << pro << " server_ip server_port\n";
    std::cout << "Usage:\n\t" << pro << "server_ip server_port\n";
}

// 客户端需要实现收消息和发消息是同步的 需要使用多线程 可以发消息的同时也能够收消息
int main(int argn, char *argv[])
{
    if (argn < 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建socket
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        LOG(FATAL, "socket error");
        exit(2);
    }

    // 构建目标主机信息
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // 申请连接
    int n = ::connect(fd, (struct sockaddr*)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error..." << std::endl;
        exit(3);
    }

    //开始通信
    while (true)
    {
        std::string outbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, outbuffer);

        ssize_t n = send(fd, outbuffer.c_str(), outbuffer.size(), 0);
        if (n > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(fd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                std::cerr << "recv error..." << std::endl;
                break;
            }
        }
        else
        {
            std::cerr << "send error..." << std::endl;
            break;
        }
    }

    ::close(fd);
    return 0;
}
